package transfer;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @author Alvaro
 */
@WebServlet(name="transfermoney_process3", urlPatterns={"/transfermoney_process3"})
public class transfermoney_process3 extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String email_S = request.getParameter("email3"); //source
        String email_D = request.getParameter("email4"); //destino
        String account_S = request.getParameter("account3"); //source
        String account_D = request.getParameter("account4"); //destino
        String money = request.getParameter("money2");
        String description = request.getParameter("description");


        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>TRANSFER TO | "+email_D+"</title>");
            out.println("<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"favicon.ico\">");

            out.println("</head>");
            out.println("<body bgcolor=\"#CCC\">");
            out.println("<h1>TRANSFER PROCESS FROM "+email_S+" TO "+email_D+"</h1>");
            out.println("<table align=\"right\" border=\"1\">");
            out.println("<tr align=\"center\">Email Source: "+ email_S+"</tr>");
            out.println("<tr align=\"center\">Email Dest: "+ email_D+"</tr>");
            out.println("<br><tr align=\"center\">Amount entered: "+ money +"</tr>");
            out.println("</table>");


            //Acceso a la base de datos para comprobar datos de usuario
            ////////////////////////////////////////////////////////////////////Añadimos los datos a la base de datos

            final String url = "jdbc:mysql://localhost:3306/payment-users";
            final String usuario = "root";
            final String passwd = "tintin";


            Connection connection = null;

            try {
              Class.forName("com.mysql.jdbc.Driver");
              connection = DriverManager.getConnection(url, "root", "tintin");

              Statement buscarUsuario = connection.createStatement();
              float balance_actual=0;
              int count=0;
              ResultSet resultado = buscarUsuario.executeQuery("SELECT * FROM `payment-users`.`user` WHERE email='"+email_S+"'");
              while (resultado.next()) {
              System.out.println("Name: " + resultado.getString("name"));
              System.out.println("Lastname: " + resultado.getString("lastname"));
              balance_actual=resultado.getFloat("money");
              System.out.println("Actual Balance:" + balance_actual);
              System.out.println("Money to transfer: " + Float.valueOf(money));
              ++count;
              }

              System.out.println("Results : "+count);
              
            if(count > 0 && balance_actual >= Float.valueOf(money))
            {
                
                out.println("EVERYTHING IS OK!");

                String updateSourceMoney = "update `payment-users`.`user` set money = money-"+money+" where email = '"+email_S+"'";
                String updateDestinationMoney = "update `payment-users`.`user` set money = money+"+money+" where email = '"+email_D+"'";
                
                String insertSourceMov = "INSERT INTO `payment-users`.`movement` (operation, money, email, account, emailTO, accountTO, description, emailowner) "
                        + "VALUES ('subtract money',"+money+",'"+email_S+"','"+account_S+"','"+email_D+"','"+account_D+"','"+description+"', '"+email_S+"')"; 
                String insertDestinationMov = "INSERT INTO `payment-users`.`movement` (operation, money, email, account, emailTO, accountTO, description, emailowner) "
                        + "VALUES ('add money',"+money+",'"+email_S+"','"+account_S+"','"+email_D+"','"+account_D+"','"+description+"', '"+email_D+"')"; 
                
                
                 String insertSourceMovTransfer = "INSERT INTO `payment-users`.`movement-transfer` (operation, money, account, accountTO, description, emailowner) "
                        + "VALUES ('subtract money',"+money+",'"+account_S+"','"+account_D+"','"+description+"', '"+email_S+"')"; 
                String insertDestinationMovTransfer = "INSERT INTO `payment-users`.`movement-transfer` (operation, money, account, accountTO, description, emailowner) "
                        + "VALUES ('add money',"+money+",'"+account_S+"','"+account_D+"','"+description+"', '"+email_D+"')"; 
                
                
                
                Statement stmt = connection.createStatement();
                
		try {
			stmt = connection.createStatement();
	   		stmt.executeUpdate(updateSourceMoney);
                        stmt.executeUpdate(updateDestinationMoney);
                        stmt.executeUpdate(insertSourceMov);
                        stmt.executeUpdate(insertDestinationMov);
                        stmt.executeUpdate(insertSourceMovTransfer);
                        stmt.executeUpdate(insertDestinationMovTransfer);

			stmt.close();
			connection.close();

		} catch(SQLException ex) {
			System.err.println("SQLException: " + ex.getMessage());
                        System.out.println("You dont have enough money!");
		}
                
            ////////////////////////////////////////////////////////////////////COOKIES
            if(email_S==null) email_S="";
            

            Date now = new Date();
            String timestamp = now.toString();

            Cookie cookie1 = new Cookie ("email",email_S);
            cookie1.setMaxAge(365 * 24 * 60 * 60);
            response.addCookie(cookie1);

            ////////////////////////////////////////////////////////////////////COOKIES
            out.println("<meta http-equiv=\"Refresh\" content=\"5;url=/Payment_System-war/transfer.jsp\">");

            }
            else
            {
                out.println("<br><br><h1>You dont have enough money!!!!!!!</h1>");
                out.println("<br><br>You are being redirected to the main page");
                out.println("<meta http-equiv=\"Refresh\" content=\"5;url=/Payment_System-war/transfer.jsp\">");
            }


              buscarUsuario.close();
              connection.close();

            } catch (SQLException e) {
              System.out.println("Error de MySQL: " + e.getMessage());
              out.println("<label>Internar error! try again later!"+e.getMessage()+"</label>");
            } catch (Exception e) {
              System.out.println("Error inesperado: " + e.getMessage());
              out.println("<label>Internar error! try again later!"+e.getMessage()+"</label>");
            }



            ////////////////////////////////////////////////////////////////////Añadimos los datos a la base de datos



            out.println("</body>");
            out.println("</html>");
            
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
